#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.application import MIMEApplication  # 发送附件
from WebSite.tools.ReadConfig import ConfigTool
from email.mime.multipart import MIMEMultipart  # 发送多个部分

class EmailTool(object):

    def __init__(self):
        fkey = 'email'
        self.conf = ConfigTool()
        self.conf.build_path(self.conf.get_current_path() + r'\..\config\config.ini')
        self.sender = self.conf.get(fkey, 'sender')
        self.password = self.conf.get(fkey, 'password')
        self.receiver = self.conf.get(fkey, 'receiver').split(',')

    def __do_mail(self, subject, content, type):
        """
        :param subject: 邮件的主题，也可以说是标题
        :param content: 内容
        :param type:
        :return:
        """
        try:
            msg = MIMEText(content, type, 'utf-8')
            msg['From'] = formataddr(("发送人", 'utf-8'))
            msg['To'] = formataddr(("接收人", 'utf-8'))
            msg['Subject'] = subject
            msg = MIMEMultipart()  # 邮件体
            # 构建附件
            att = MIMEApplication(open(self.conf.build_path, 'rb').read())  # 打开附件
            att.add_header("Content-Disposition", "attachment", filename='测试报告.html')  # 为附件命名
            msg.attach(att)  # 添加附件到邮件体中

            server = smtplib.SMTP_SSL("smtp.qq.com", 465)
            server.login(self.sender, self.password)
            server.sendmail(self.sender, self.receiver, msg.as_string())
            server.quit()
        except NameError:
            return False
        return True

    def mail_html(self, subject, content):
        return self.__do_mail(subject, content, 'html')

    def mail_text(self, subject, content):
        return self.__do_mail(subject, content, 'plain')


if __name__ == '__main__':
    t = EmailTool()
    print(t.mail_text('subjectTest2', 'conterntTest2'))
    # print(t.mail_html('subjectTest2', '<p>htmlcontent</p>'))
